package cn.com.ctcloud.microservice.dynamicds.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import cn.com.ctcloud.microservice.dynamicds.SaasDynamicDatasource;
import cn.com.ctcloud.microservice.dynamicds.database.druid.DruidDBConfig;
import cn.com.ctcloud.microservice.dynamicds.filter.InterceptorRegister;
import cn.com.ctcloud.microservice.dynamicds.filter.OrganCodeInterceptor;

/**
 * Title: 分布式动态数据源路由
 * <p>
 * Description: 动态数据源自动配置类
 * <p>
 * Copyright: Copyright (c) 2008
 * <p>
 * Company: Liaoning Open Data Communication Co.,Ltd.
 * 
 * @author lihui
 * @version 1.0.0
 */
@Configuration
@EnableConfigurationProperties(DynamicDatasourceConfigProperties.class) // 把配置读取类注入到本自动配置类
public class DynamicDSAutoConfiguration {

	@Autowired
	private DynamicDatasourceConfigProperties properties;

	@Autowired(required = false)
	private DruidDBConfig druidDBConfig;

	@Bean
	@ConditionalOnMissingBean // 只有不存在同名同类bean时，此bean才生效
	@ConditionalOnClass(SaasDynamicDatasource.class) //只有classpath中存在SaasDynamicDatasource类时，此bean才生效。
	DataSource dataSource() {
		SaasDynamicDatasource ds = new SaasDynamicDatasource();
		ds.setDsProperties(properties, druidDBConfig);
		return ds;
	}

	@Bean
	@ConditionalOnMissingBean
	@ConditionalOnClass(SaasDynamicDatasource.class)
	OrganCodeInterceptor organCodeInterceptor() {
		OrganCodeInterceptor interceptor = new OrganCodeInterceptor();
		interceptor.setOrganCodeHeaderName(properties.getOrganCodeHeader());
		interceptor.setValidOrgCodes(properties.getTenants().keySet());
		return interceptor;
	}

	@Bean
	@ConditionalOnMissingBean
	@ConditionalOnClass(SaasDynamicDatasource.class)
	InterceptorRegister interceptorRegister() {
		InterceptorRegister interceptorRegister = new InterceptorRegister();
		return interceptorRegister;
	}
}
